import 'package:chathouse/constant/my_color.dart';
import 'package:chathouse/util/font_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:chathouse/util/base_utils.dart';
import 'form_widgets/widget_paras.dart';
import 'package:dropdown_button2/dropdown_button2.dart';

typedef MyDropDownWidgetItemChange = Function(String val);

class MyDropDownWidget extends StatefulWidget {
  String placeholder;
  String? selectedValue;
  List<MyDropDownBean> initValue;
  MyDropDownWidgetItemChange onSelectedItemChange;

  String? get getSelectedItemName {
    String? name;
    for (var element in initValue) {
      if (element.value == selectedValue) {
        name = element.name;
      }
    }
    return name;
  }

  MyDropDownWidget(
      this.selectedValue, this.initValue, this.onSelectedItemChange,
      {this.placeholder = "請選擇", Key? key})
      : super(key: key);

  @override
  State<MyDropDownWidget> createState() => _MyDropDownWidgetState();
}

class _MyDropDownWidgetState extends State<MyDropDownWidget> {
  @override
  Widget build(BuildContext context) {
    return DropdownButton2(
      customButton: Container(
        height: INPUT_ITEM_HEIGHT.w,
        padding: EdgeInsets.symmetric(horizontal: 12.w),
        decoration: BoxDecoration(
            border: Border.all(color: MyColors.gary_155155155, width: 1.w),
            borderRadius: BorderRadius.circular(INPUT_ITEM_BORDER_RADIUS.w)),
        child: Row(
          children: [
            Expanded(
              child: Text(
                widget.getSelectedItemName ?? widget.placeholder,
                style: getTextStyle(16.sp,
                    color: widget.getSelectedItemName == null
                        ? MyColors.gary_155155155
                        : Colors.black,
                    fontType: FontType.DEFAULT),
              ),
            ),
            Icon(
              Icons.keyboard_arrow_down_rounded,
              size: 20.w,
              color: MyColors.gary_112112112,
            )
          ],
        ),
      ),
      items: widget.initValue.map((e) {
        return DropdownMenuItem<String>(
          value: e.value,
          child: Text(
            e.name,
            style: getTextStyle(16.sp,
                color: Colors.black, fontType: FontType.DEFAULT),
          ),
        );
      }).toList(),
      itemHeight: INPUT_ITEM_HEIGHT.w,
      value: widget.selectedValue,
      onChanged: (val) {
        setState(() {
          widget.selectedValue = "$val";
        });
        widget.onSelectedItemChange("$val");
      },
      underline: Container(),
    );
  }
}

class MyDropDownBean {
  String value;
  String name;
  MyDropDownBean(this.value, this.name);
}
